package com.example.androiddemo.day719;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.androiddemo.R;

public class SharedPreferenceActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText mInputName, mInputPassword;
    private TextView mShowName, mShowPassword;
    private Button mSaveData, mReadData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preference);
        initView();
    }

    private void initView(){
        mInputName=findViewById(R.id.input_name);
        mInputPassword=findViewById(R.id.input_password);
        mShowName=findViewById(R.id.show_name);
        mShowPassword=findViewById(R.id.show_password);
        mSaveData=findViewById(R.id.save_data);
        mReadData=findViewById(R.id.read_data);
        mSaveData.setOnClickListener(this);
        mReadData.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.save_data:
                SharedPreferences sp=getSharedPreferences("user",MODE_PRIVATE);
                SharedPreferences.Editor pe=sp.edit();
                pe.putString("NAME",mInputName.getText().toString());
                pe.putString("PASSWORD",mInputPassword.getText().toString());
                pe.apply();
                Toast.makeText(this,"用户信息保存成功！",Toast.LENGTH_SHORT).show();
                break;
            case R.id.read_data:
                SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
                mShowName.setText(sharedPreferences.getString("NAME","zhangqiang"));
                mShowPassword.setText(sharedPreferences.getString("PASSWORD","123456"));
                break;
            default:
                break;
        }
    }
}